package com.edu.lawdoc.dao;


import java.util.*;
import java.util.stream.Collectors;

public class Filter {
    Map<String, Field> map = new HashMap<>();


    public void put(String key, Object value) {
        this.put(key, value, Field.Action.EQUALS);
    }

    public void put(String key, Object value, Field.Action action) {
        if(value == null) {
            return;
        }

        if(action == Field.Action.LIKE) {
            value = value + "%";
        }

        Field oField = new Field();
        oField.setKey(key);
        oField.setValue(value);
        oField.setAction(action);
        map.put(key, oField);
    }

    /**
     * 使用索引，会默认把使用索引的字段放到最前面
     * @param columns
     * @return
     */
    public Filter useDataBaseIndex(String ... columns) {
        for(int i = 0; i < columns.length; i++) {
            String column = columns[i];
            Field field = map.get(column);
            if(field != null) {
                field.setOrder(columns.length - i);
            }
        }

        return this;
    }

    /**
     * 使用了索引的就会排在最前面
     * @return
     */
    public List<Field> getPara() {
        List<Field> list = map.values().stream().collect(Collectors.toList());
        Collections.sort(list, (o1, o2) -> {
            // 返回值为int类型，大于0表示正序，小于0表示逆序
            return o2.getOrder() - o1.getOrder();
        });
        return list;
    }
}
